package com.hanhai.material.device.utils.kingdee;

import cn.hutool.core.map.MapBuilder;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hanhai.material.common.result.KingdeeResult;
import com.hanhai.material.device.entity.*;
import com.hanhai.material.device.model.TokenModel;
import com.hanhai.material.device.model.miscellaneousdelivery.*;
import com.hanhai.material.device.model.miscellaneousdelivery.FDCSPID;
import com.hanhai.material.device.model.pick.*;
import com.hanhai.material.device.model.pick.Data;
import com.hanhai.material.device.model.pick.FDeptID;
import com.hanhai.material.device.model.pick.FFManagerID;
import com.hanhai.material.device.model.pick.FItemID;
import com.hanhai.material.device.model.pick.FSManagerID;
import com.hanhai.material.device.model.pick.FUnitID;
import com.hanhai.material.device.model.pick.Page1;
import com.hanhai.material.device.model.pick.Page2;
import com.hanhai.material.device.service.*;
import com.hanhai.material.model.bom.Bom;
import com.hanhai.material.utils.redis.RedisUtil;
import com.mybatisflex.core.query.QueryWrapper;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.YearMonth;
import java.time.ZoneId;
import java.util.*;

import static com.hanhai.material.device.entity.table.SysBadRecordTableDef.SYS_BAD_RECORD;
import static com.hanhai.material.device.entity.table.SysBomTableDef.SYS_BOM;
import static com.hanhai.material.device.entity.table.SysProductRecordShiftTableDef.SYS_PRODUCT_RECORD_SHIFT;
import static com.hanhai.material.device.entity.table.SysProductRecordTableDef.SYS_PRODUCT_RECORD;
import static com.hanhai.material.utils.TimeUtils.fromDateToString;
import static com.hanhai.material.utils.TimeUtils.getDatesOfMonth;
import static com.mybatisflex.core.query.QueryMethods.sum;

;

@Log4j2
@Component
public class KingdeeUtils {
    @Value("${kingdee.baseUrl}")
    String baseUrl;
    @Value("${kingdee.authorityCode}")
    String authorityCode;

    @Value("${kingdee.fmanagerid}")
    private String fManagerId;
    @Value("${kingdee.smanagerid}")
    private String sManagerId;
    @Autowired
    RedisUtil redisUtil;

    /**
     * 生成金蝶Token
     *
     * @return
     * @throws IOException
     */

    public String createToken() throws IOException {
        String url = baseUrl + "/Token/Create?authorityCode=" + authorityCode;
        HttpHeaders headers = new HttpHeaders();
        RestTemplate restTemplate = new RestTemplate();
        MediaType type = MediaType.parseMediaType("application/json;charset=UTF-8");
        headers.setContentType(type);
        Map<Object, Object> map = new HashMap<>();
        HttpEntity<Map<Object, Object>> httpEntity = new HttpEntity<>(map, headers);
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, httpEntity, String.class);
        JSONObject jsonObject = JSON.parseObject(responseEntity.getBody());
        TokenModel tokenModel = jsonObject.getObject("Data", TokenModel.class);
        this.redisUtil.set("token-king", tokenModel.getToken(), tokenModel.getValidity());
        return tokenModel.getToken();
    }

    public String createToken1() throws IOException {
        String url = baseUrl + "/Token/Create?authorityCode=" + authorityCode;
        HttpHeaders headers = new HttpHeaders();
        RestTemplate restTemplate = new RestTemplate();
        MediaType type = MediaType.parseMediaType("application/json;charset=UTF-8");
        headers.setContentType(type);
        Map<Object, Object> map = new HashMap<>();
        HttpEntity<Map<Object, Object>> httpEntity = new HttpEntity<>(map, headers);
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, httpEntity, String.class);
        JSONObject jsonObject = JSON.parseObject(responseEntity.getBody());
        TokenModel tokenModel = jsonObject.getObject("Data", TokenModel.class);
        this.redisUtil.set("token-king-device", tokenModel.getToken(), tokenModel.getValidity());
        return tokenModel.getToken();
    }


    public JSONObject getMaterialInfo(String materialId) throws IOException {
        String token = this.createToken();
        String url = baseUrl + "/Material/GetDetail?token=" + token;
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json;charset=UTF-8");
        headers.setContentType(type);
        Map<Object, Object> map = MapBuilder.create().put("Data",
                MapBuilder.create().put("FNumber", materialId).build()).build();
        HttpEntity<Map<Object, Object>> httpEntity = new HttpEntity<>(map, headers);
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, httpEntity, String.class);
        JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(responseEntity));
        JSONObject body = jsonObject.getJSONObject("body");
        log.error("Json:" + body);
        return body;
    }

    public KingdeeResult addMaterialInfo(MiscellaneousDelivery miscellaneousDelivery) throws IOException {

        String token = this.createToken();
        String url = baseUrl + "/Miscellaneous_Delivery/Save?token=" + token;
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json;charset=UTF-8");
        headers.setContentType(type);
        HttpEntity<MiscellaneousDelivery> httpEntity = new HttpEntity<>(miscellaneousDelivery, headers);
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, httpEntity, String.class);
        JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(responseEntity));
        log.error("Json:{}", JSONObject.toJSONString(jsonObject.getJSONObject("body")));
        return JSONObject.parseObject(JSONObject.toJSONString(jsonObject.getJSONObject("body")), KingdeeResult.class);
    }

    public KingdeeResult updateMaterialInfo(UpdateMiscellaneousDelivery miscellaneousDelivery) throws IOException {

        String token = this.createToken();
        String url = baseUrl + "/Miscellaneous_Delivery/Update?token=" + token;
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json;charset=UTF-8");
        headers.setContentType(type);
        HttpEntity<UpdateMiscellaneousDelivery> httpEntity = new HttpEntity<>(miscellaneousDelivery, headers);
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, httpEntity, String.class);
        JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(responseEntity));
        log.error("Json:{}", JSONObject.toJSONString(jsonObject.getJSONObject("body")));
        return JSONObject.parseObject(JSONObject.toJSONString(jsonObject.getJSONObject("body")), KingdeeResult.class);
    }
    public KingdeeResult deleteMaterialInfo(String billno) throws IOException {

        String token = this.createToken();
        String url = baseUrl + "/Miscellaneous_Delivery/Delete?token=" + token;
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json;charset=UTF-8");
        headers.setContentType(type);
        Map<Object,Object> map=new HashMap<>();
        map.put("Data",MapBuilder.create().put("FBillNo",billno).build());
        HttpEntity<Map<Object,Object>> httpEntity = new HttpEntity<>(map, headers);
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, httpEntity, String.class);
        JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(responseEntity));
        log.error("Json:{}", JSONObject.toJSONString(jsonObject.getJSONObject("body")));
        return JSONObject.parseObject(JSONObject.toJSONString(jsonObject.getJSONObject("body")), KingdeeResult.class);
    }

    public MiscellaneousDelivery getMiscellaneousDeliveryList(List<SysDocument> documentList) {
        if (documentList.isEmpty()) {
            return null;
        }
        com.hanhai.material.device.model.miscellaneousdelivery.Data data = new com.hanhai.material.device.model.miscellaneousdelivery.Data();
        SysDocument sysDocument = documentList.get(0);
        MiscellaneousDelivery miscellaneousDelivery = new MiscellaneousDelivery();
        com.hanhai.material.device.model.miscellaneousdelivery.Page1 page1 = new com.hanhai.material.device.model.miscellaneousdelivery.Page1();

        /*红蓝标志*/
        page1.setFROB("1");
        /*领料部门*/
        com.hanhai.material.device.model.miscellaneousdelivery.FDeptID fDeptID = new com.hanhai.material.device.model.miscellaneousdelivery.FDeptID();
        fDeptID.setFNumber("11");
        fDeptID.setFName("");
        page1.setFDeptID(fDeptID);

        SysDocument documentObj=documentList.get(0);
        page1.setFROB(documentObj.getFrob().toString());

        /*日期*/
        page1.setFdate(fromDateToString("yyyy-MM-dd 00:00:00", sysDocument.getCollectionDate()));
        /*发货仓库*/
        FDCStockID fdcStockID = new FDCStockID();
        fdcStockID.setFNumber("MF");
        fdcStockID.setFName("");
        page1.setFDCStockID(fdcStockID);
        /*领料人*/
        com.hanhai.material.device.model.miscellaneousdelivery.FFManagerID ffManagerID = new com.hanhai.material.device.model.miscellaneousdelivery.FFManagerID();
        ffManagerID.setFName("");
        ffManagerID.setFNumber("HZ06415");
        page1.setFFManagerID(ffManagerID);


        page1.setFSelTranType("706");

        /*发货人*/
        com.hanhai.material.device.model.miscellaneousdelivery.FSManagerID fsManagerID = new com.hanhai.material.device.model.miscellaneousdelivery.FSManagerID();
        fsManagerID.setFName("");
        fsManagerID.setFNumber("HJ00027");
        page1.setFSManagerID(fsManagerID);
        page1.setFHeadSelfB0944(sysDocument.getCreateUserName());
        List<com.hanhai.material.device.model.miscellaneousdelivery.Page1> page1List = new ArrayList<>();
        page1List.add(page1);
        List<com.hanhai.material.device.model.miscellaneousdelivery.Page2> page2List = new ArrayList<>();
        int i = 0;

        for (SysDocument document : documentList) {
            i++;
            com.hanhai.material.device.model.miscellaneousdelivery.Page2 page2 = new com.hanhai.material.device.model.miscellaneousdelivery.Page2();
            /*行号*/
            page2.setFEntryID2(String.valueOf(i));
            /*产品代码*/
            com.hanhai.material.device.model.miscellaneousdelivery.FItemID fItemID = new com.hanhai.material.device.model.miscellaneousdelivery.FItemID();
            fItemID.setFName("");
            fItemID.setFNumber(document.getMaterialId());
            page2.setFItemID(fItemID);
            /*产品名称*/
            page2.setFItemName(document.getMaterialName());
            /*单位*/
            com.hanhai.material.device.model.miscellaneousdelivery.FUnitID fUnitID = new com.hanhai.material.device.model.miscellaneousdelivery.FUnitID();
            fUnitID.setFName("");
            fUnitID.setFNumber(String.valueOf(document.getUnitId()));
            page2.setFUnitID(fUnitID);
            page2.setFSourceTranType("37521");

            /*数量*/
            page2.setFauxqty(String.valueOf(document.getNum()));
            page2.setFQty(String.valueOf(document.getNum()));
            page2.setFnote(document.getUseNote());

            /*发货仓库*/
            FDCStockID1 fdcStockID1 = new FDCStockID1();
            fdcStockID1.setFNumber("MF");
            fdcStockID1.setFName("");
            page2.setFDCStockID1(fdcStockID1);
            page2.setFEntrySelfB0952(document.getCreateUserName());

            FDCSPID fdcspid=new FDCSPID();
            fdcspid.setFName("BH1095");
            fdcspid.setFNumber("BH1095");
            page2.setFDCSPID(fdcspid);

            /*计划模式*/
            com.hanhai.material.device.model.miscellaneousdelivery.FPlanMode fPlanMode = new com.hanhai.material.device.model.miscellaneousdelivery.FPlanMode();
            fPlanMode.setFNumber("MTS");
            fPlanMode.setFName("");

            page2.setFPlanMode(fPlanMode);

            page2List.add(page2);
        }
        data.setPage1(page1List);
        data.setPage2(page2List);
        miscellaneousDelivery.setData(data);
        return miscellaneousDelivery;
    }

    public UpdateMiscellaneousDelivery getUpdateMiscellaneousDeliveryList(List<SysDocument> documentList) {
        if (documentList.isEmpty()) {
            return null;
        }
        com.hanhai.material.device.model.miscellaneousdelivery.Data data = new com.hanhai.material.device.model.miscellaneousdelivery.Data();
        SysDocument sysDocument = documentList.get(0);
        UpdateMiscellaneousDelivery miscellaneousDelivery = new UpdateMiscellaneousDelivery();
        com.hanhai.material.device.model.miscellaneousdelivery.Page1 page1 = new com.hanhai.material.device.model.miscellaneousdelivery.Page1();

        /*红蓝标志*/
        page1.setFROB("1");
        /*领料部门*/
        com.hanhai.material.device.model.miscellaneousdelivery.FDeptID fDeptID = new com.hanhai.material.device.model.miscellaneousdelivery.FDeptID();
        fDeptID.setFNumber("11");
        fDeptID.setFName("");
        page1.setFDeptID(fDeptID);

        SysDocument documentObj=documentList.get(0);
        page1.setFROB(documentObj.getFrob().toString());


        /*日期*/
        page1.setFdate(fromDateToString("yyyy-MM-dd 00:00:00", sysDocument.getCollectionDate()));
        /*发货仓库*/
        FDCStockID fdcStockID = new FDCStockID();
        fdcStockID.setFNumber("MF");
        fdcStockID.setFName("");
        page1.setFDCStockID(fdcStockID);
        /*领料人*/
        com.hanhai.material.device.model.miscellaneousdelivery.FFManagerID ffManagerID = new com.hanhai.material.device.model.miscellaneousdelivery.FFManagerID();
        ffManagerID.setFName("");
        ffManagerID.setFNumber("HZ06415");
        page1.setFFManagerID(ffManagerID);



        page1.setFSelTranType("706");

        /*发货人*/
        com.hanhai.material.device.model.miscellaneousdelivery.FSManagerID fsManagerID = new com.hanhai.material.device.model.miscellaneousdelivery.FSManagerID();
        fsManagerID.setFName("");
        fsManagerID.setFNumber("HJ00027");
        page1.setFSManagerID(fsManagerID);
        page1.setFHeadSelfB0944(sysDocument.getCreateUserName());
        page1.setFBillNo(sysDocument.getKingNo());
        List<com.hanhai.material.device.model.miscellaneousdelivery.Page1> page1List = new ArrayList<>();
        page1List.add(page1);
        List<com.hanhai.material.device.model.miscellaneousdelivery.Page2> page2List = new ArrayList<>();
        int i = 0;

        for (SysDocument document : documentList) {
            i++;
            com.hanhai.material.device.model.miscellaneousdelivery.Page2 page2 = new com.hanhai.material.device.model.miscellaneousdelivery.Page2();
            /*行号*/
            page2.setFEntryID2(String.valueOf(i));
            /*产品代码*/
            com.hanhai.material.device.model.miscellaneousdelivery.FItemID fItemID = new com.hanhai.material.device.model.miscellaneousdelivery.FItemID();
            fItemID.setFName("");
            fItemID.setFNumber(document.getMaterialId());
            page2.setFItemID(fItemID);
            /*产品名称*/
            page2.setFItemName(document.getMaterialName());
            /*单位*/
            com.hanhai.material.device.model.miscellaneousdelivery.FUnitID fUnitID = new com.hanhai.material.device.model.miscellaneousdelivery.FUnitID();
            fUnitID.setFName("");
            fUnitID.setFNumber(String.valueOf(document.getUnitId()));
            page2.setFUnitID(fUnitID);
            page2.setFSourceTranType("37521");

            /*数量*/
            page2.setFauxqty(String.valueOf(document.getNum()));
            page2.setFQty(String.valueOf(document.getNum()));
            page2.setFnote(document.getUseNote());

            /*发货仓库*/
            FDCStockID1 fdcStockID1 = new FDCStockID1();
            fdcStockID1.setFNumber("MF");
            fdcStockID1.setFName("");
            page2.setFDCStockID1(fdcStockID1);

            FDCSPID fdcspid=new FDCSPID();
            fdcspid.setFName("BH1095");
            fdcspid.setFNumber("BH1095");
            page2.setFDCSPID(fdcspid);
            /*计划模式*/
            com.hanhai.material.device.model.miscellaneousdelivery.FPlanMode fPlanMode = new com.hanhai.material.device.model.miscellaneousdelivery.FPlanMode();
            fPlanMode.setFNumber("MTS");
            fPlanMode.setFName("");

            page2.setFEntrySelfB0952(document.getCreateUserName());

            page2.setFPlanMode(fPlanMode);

            page2List.add(page2);
        }
        data.setPage1(page1List);
        data.setPage2(page2List);
        miscellaneousDelivery.setFBillNo(sysDocument.getKingNo());
        miscellaneousDelivery.setData(data);
        return miscellaneousDelivery;
    }

    public MiscellaneousDelivery getMiscellaneousDelivery(SysDocument document) {
        if (document == null) {
            return null;
        }
        com.hanhai.material.device.model.miscellaneousdelivery.Data data = new com.hanhai.material.device.model.miscellaneousdelivery.Data();

        MiscellaneousDelivery miscellaneousDelivery = new MiscellaneousDelivery();
        com.hanhai.material.device.model.miscellaneousdelivery.Page1 page1 = new com.hanhai.material.device.model.miscellaneousdelivery.Page1();

        /*红蓝标志*/
        page1.setFROB("1");
        /*领料部门*/
        com.hanhai.material.device.model.miscellaneousdelivery.FDeptID fDeptID = new com.hanhai.material.device.model.miscellaneousdelivery.FDeptID();
        fDeptID.setFNumber("11");
        fDeptID.setFName("");
        page1.setFDeptID(fDeptID);

        /*日期*/
        page1.setFdate(fromDateToString("yyyy-MM-dd 00:00:00", document.getCollectionDate()));
        /*发货仓库*/
        FDCStockID fdcStockID = new FDCStockID();
        fdcStockID.setFNumber("MF");
        fdcStockID.setFName("");
        page1.setFDCStockID(fdcStockID);
        /*领料人*/
        com.hanhai.material.device.model.miscellaneousdelivery.FFManagerID ffManagerID = new com.hanhai.material.device.model.miscellaneousdelivery.FFManagerID();
        ffManagerID.setFName("");
        ffManagerID.setFNumber("HZ06415");
        page1.setFFManagerID(ffManagerID);



        page1.setFSelTranType("706");

        page1.setFROB(document.getFrob().toString());

        /*发货人*/
        com.hanhai.material.device.model.miscellaneousdelivery.FSManagerID fsManagerID = new com.hanhai.material.device.model.miscellaneousdelivery.FSManagerID();
        fsManagerID.setFName("");
        fsManagerID.setFNumber("HJ00027");
        page1.setFSManagerID(fsManagerID);
        page1.setFHeadSelfB0944(document.getCreateUserName());
        List<com.hanhai.material.device.model.miscellaneousdelivery.Page1> page1List = new ArrayList<>();
        page1List.add(page1);
        List<com.hanhai.material.device.model.miscellaneousdelivery.Page2> page2List = new ArrayList<>();
        int i = 1;

        com.hanhai.material.device.model.miscellaneousdelivery.Page2 page2 = new com.hanhai.material.device.model.miscellaneousdelivery.Page2();
        /*行号*/
        page2.setFEntryID2(String.valueOf(i));
        /*产品代码*/
        com.hanhai.material.device.model.miscellaneousdelivery.FItemID fItemID = new com.hanhai.material.device.model.miscellaneousdelivery.FItemID();
        fItemID.setFName("");
        fItemID.setFNumber(document.getMaterialId());
        page2.setFItemID(fItemID);
        /*产品名称*/
        page2.setFItemName(document.getMaterialName());
        /*单位*/
        com.hanhai.material.device.model.miscellaneousdelivery.FUnitID fUnitID = new com.hanhai.material.device.model.miscellaneousdelivery.FUnitID();
        fUnitID.setFName("");
        fUnitID.setFNumber(String.valueOf(document.getUnitId()));
        page2.setFUnitID(fUnitID);
        page2.setFSourceTranType("37521");

        /*数量*/
        page2.setFauxqty(String.valueOf(document.getNum()));
        page2.setFQty(String.valueOf(document.getNum()));
        page2.setFnote(document.getUseNote());

        /*发货仓库*/
        FDCStockID1 fdcStockID1 = new FDCStockID1();
        fdcStockID1.setFNumber("MF");
        fdcStockID1.setFName("");
        page2.setFDCStockID1(fdcStockID1);

        FDCSPID fdcspid=new FDCSPID();
        fdcspid.setFName("BH1095");
        fdcspid.setFNumber("BH1095");
        page2.setFDCSPID(fdcspid);

        /*计划模式*/
        com.hanhai.material.device.model.miscellaneousdelivery.FPlanMode fPlanMode = new com.hanhai.material.device.model.miscellaneousdelivery.FPlanMode();
        fPlanMode.setFNumber("MTS");
        fPlanMode.setFName("");

        page2.setFEntrySelfB0952(document.getCreateUserName());


        page2.setFPlanMode(fPlanMode);

        page2.setFnote(document.getNote());
        page2List.add(page2);


        data.setPage1(page1List);
        data.setPage2(page2List);
        miscellaneousDelivery.setData(data);
        return miscellaneousDelivery;
    }

    @Autowired
    SysBadRecordService sysBadRecordService;

    public MiscellaneousDelivery getMiscellaneousDelivery1(List<SysProductRecordInto> productRecordIntoList) {
        if (productRecordIntoList.isEmpty()) {
            return null;
        }
        log.error("其他出库单");
        SysProductRecordInto productRecordInto=productRecordIntoList.get(0);
        com.hanhai.material.device.model.miscellaneousdelivery.Data data = new com.hanhai.material.device.model.miscellaneousdelivery.Data();

        MiscellaneousDelivery miscellaneousDelivery = new MiscellaneousDelivery();
        com.hanhai.material.device.model.miscellaneousdelivery.Page1 page1 = new com.hanhai.material.device.model.miscellaneousdelivery.Page1();

        /*红蓝标志*/
        page1.setFROB("1");
        /*领料部门*/
        com.hanhai.material.device.model.miscellaneousdelivery.FDeptID fDeptID = new com.hanhai.material.device.model.miscellaneousdelivery.FDeptID();
        fDeptID.setFNumber("04");
        fDeptID.setFName("");
        page1.setFDeptID(fDeptID);

        /*日期*/
        page1.setFdate(fromDateToString("yyyy-MM-dd 00:00:00", productRecordInto.getProductDate()));
        /*发货仓库*/
        FDCStockID fdcStockID = new FDCStockID();
        fdcStockID.setFNumber("IN1.057");
        fdcStockID.setFName("");
        page1.setFDCStockID(fdcStockID);


        /*领料人*/
        com.hanhai.material.device.model.miscellaneousdelivery.FFManagerID ffManagerID = new com.hanhai.material.device.model.miscellaneousdelivery.FFManagerID();
        ffManagerID.setFName("吴思富");
        ffManagerID.setFNumber("HZ05707");
        page1.setFFManagerID(ffManagerID);
        page1.setFSelTranType("706");

        /*发货人*/
        com.hanhai.material.device.model.miscellaneousdelivery.FSManagerID fsManagerID = new com.hanhai.material.device.model.miscellaneousdelivery.FSManagerID();
        fsManagerID.setFName("");
        fsManagerID.setFNumber("HZ05707");
        page1.setFSManagerID(fsManagerID);
        page1.setFHeadSelfB0944("吴思富");
        List<com.hanhai.material.device.model.miscellaneousdelivery.Page1> page1List = new ArrayList<>();
        page1List.add(page1);
        List<com.hanhai.material.device.model.miscellaneousdelivery.Page2> page2List = new ArrayList<>();
        int i = 1;
        for(SysProductRecordInto recordInto:productRecordIntoList) {
            SysWorkPlan workPlan=recordInto.getWorkPlan();

            com.hanhai.material.device.model.miscellaneousdelivery.Page2 page2 = new com.hanhai.material.device.model.miscellaneousdelivery.Page2();
            /*行号*/
            page2.setFEntryID2(String.valueOf(i));
            /*产品代码*/
            com.hanhai.material.device.model.miscellaneousdelivery.FItemID fItemID = new com.hanhai.material.device.model.miscellaneousdelivery.FItemID();
            fItemID.setFName("");
            fItemID.setFNumber(workPlan.getProductId());
            page2.setFItemID(fItemID);
            /*产品名称*/
            page2.setFItemName(workPlan.getProductName());
            /*单位*/
            com.hanhai.material.device.model.miscellaneousdelivery.FUnitID fUnitID = new com.hanhai.material.device.model.miscellaneousdelivery.FUnitID();
            fUnitID.setFName("");
            fUnitID.setFNumber(String.valueOf(workPlan.getUnitId()));
            page2.setFUnitID(fUnitID);
            page2.setFSourceTranType("37521");

            QueryWrapper queryWrapper = QueryWrapper.create();
            queryWrapper.where(SYS_BAD_RECORD.WORK_PLAN_ID.eq(workPlan.getWorkPlanId()));
            queryWrapper.where(SYS_BAD_RECORD.PRODUCT_DATE.eq(fromDateToString("yyyy-MM-dd",recordInto.getProductDate())));
            queryWrapper.where(SYS_BAD_RECORD.SHIFT.eq(recordInto.getShift()));
            queryWrapper.where(SYS_BAD_RECORD.REASON_TYPE.eq("品质领取"));
            queryWrapper.select(SYS_BAD_RECORD.MACHINE_NAME, SYS_BAD_RECORD.PRODUCT_ID, sum(SYS_BAD_RECORD.NUM).as("num"), SYS_BAD_RECORD.REASON_TYPE, SYS_BAD_RECORD.REASON_NAME,SYS_BAD_RECORD.TYPE);
            queryWrapper.groupBy(SYS_BAD_RECORD.REASON_TYPE, SYS_BAD_RECORD.REASON_NAME,SYS_BAD_RECORD.TYPE);
            List<SysBadRecord> badRecordList = this.sysBadRecordService.list(queryWrapper);
            StringJoiner stringJoiner = new StringJoiner(";");
            int num = 0;
            for (SysBadRecord badRecord : badRecordList) {
                if(badRecord.getType()==null){
                    badRecord.setType("不良品");
                }
                num += badRecord.getNum();
                if (badRecord.getReasonType().equals(badRecord.getReasonName())) {
                    stringJoiner.add(badRecord.getType()+badRecord.getReasonName() + badRecord.getNum() + "PCS");
                } else {
                    stringJoiner.add(badRecord.getType()+badRecord.getReasonType() + "(" + badRecord.getReasonName() + ")" + badRecord.getNum() + "PCS");
                }
            }

//            if(num<=0){
//                continue;
//            }

            /*数量*/
            page2.setFauxqty(String.valueOf(num));
            page2.setFQty(String.valueOf(num));
            page2.setFEntrySelfB0946(workPlan.getMachineName()+stringJoiner.toString());

            /*发货仓库*/
            FDCStockID1 fdcStockID1 = new FDCStockID1();
            fdcStockID1.setFNumber("IN1.057");
            fdcStockID1.setFName("");
            page2.setFDCStockID1(fdcStockID1);

            /*计划模式*/
            com.hanhai.material.device.model.miscellaneousdelivery.FPlanMode fPlanMode = new com.hanhai.material.device.model.miscellaneousdelivery.FPlanMode();
            fPlanMode.setFNumber("MTS");
            fPlanMode.setFName("");


            page2.setFPlanMode(fPlanMode);
            if (num > 0) {
                page2List.add(page2);
            }
            i++;
        }
        log.error("其他出库单数据：{}",page2List);
        data.setPage1(page1List);
        data.setPage2(page2List);
        miscellaneousDelivery.setData(data);
        return miscellaneousDelivery;
    }

    public UpdateMiscellaneousDelivery getUpdateMiscellaneousDelivery(SysDocument document) {
        if (document == null) {
            return null;
        }
        com.hanhai.material.device.model.miscellaneousdelivery.Data data = new com.hanhai.material.device.model.miscellaneousdelivery.Data();

        UpdateMiscellaneousDelivery miscellaneousDelivery = new UpdateMiscellaneousDelivery();
        com.hanhai.material.device.model.miscellaneousdelivery.Page1 page1 = new com.hanhai.material.device.model.miscellaneousdelivery.Page1();

        /*红蓝标志*/
        page1.setFROB("1");
        /*领料部门*/
        com.hanhai.material.device.model.miscellaneousdelivery.FDeptID fDeptID = new com.hanhai.material.device.model.miscellaneousdelivery.FDeptID();
        fDeptID.setFNumber("11");
        fDeptID.setFName("");
        page1.setFDeptID(fDeptID);

        /*日期*/
        page1.setFdate(fromDateToString("yyyy-MM-dd 00:00:00", document.getCollectionDate()));
        /*发货仓库*/
        FDCStockID fdcStockID = new FDCStockID();
        fdcStockID.setFNumber("MF");
        fdcStockID.setFName("");
        page1.setFDCStockID(fdcStockID);
        /*领料人*/
        com.hanhai.material.device.model.miscellaneousdelivery.FFManagerID ffManagerID = new com.hanhai.material.device.model.miscellaneousdelivery.FFManagerID();
        ffManagerID.setFName("");
        ffManagerID.setFNumber(document.getCreateUserId());
        page1.setFFManagerID(ffManagerID);
        page1.setFSelTranType("706");
        page1.setFBillNo(document.getKingNo());

        /*发货人*/
        com.hanhai.material.device.model.miscellaneousdelivery.FSManagerID fsManagerID = new com.hanhai.material.device.model.miscellaneousdelivery.FSManagerID();
        fsManagerID.setFName("");
        fsManagerID.setFNumber("HJ00027");
        page1.setFSManagerID(fsManagerID);
        page1.setFHeadSelfB0944(document.getCreateUserName());
        List<com.hanhai.material.device.model.miscellaneousdelivery.Page1> page1List = new ArrayList<>();
        page1List.add(page1);
        List<com.hanhai.material.device.model.miscellaneousdelivery.Page2> page2List = new ArrayList<>();
        int i = 1;

        com.hanhai.material.device.model.miscellaneousdelivery.Page2 page2 = new com.hanhai.material.device.model.miscellaneousdelivery.Page2();
        /*行号*/
        page2.setFEntryID2(String.valueOf(i));
        /*产品代码*/
        com.hanhai.material.device.model.miscellaneousdelivery.FItemID fItemID = new com.hanhai.material.device.model.miscellaneousdelivery.FItemID();
        fItemID.setFName("");
        fItemID.setFNumber(document.getMaterialId());
        page2.setFItemID(fItemID);
        /*产品名称*/
        page2.setFItemName(document.getMaterialName());
        /*单位*/
        com.hanhai.material.device.model.miscellaneousdelivery.FUnitID fUnitID = new com.hanhai.material.device.model.miscellaneousdelivery.FUnitID();
        fUnitID.setFName("");
        fUnitID.setFNumber(String.valueOf(document.getUnitId()));
        page2.setFUnitID(fUnitID);
        page2.setFSourceTranType("37521");

        /*数量*/
        page2.setFauxqty(String.valueOf(document.getNum()));
        page2.setFQty(String.valueOf(document.getNum()));
        page2.setFnote(document.getUseNote());

        /*发货仓库*/
        FDCStockID1 fdcStockID1 = new FDCStockID1();
        fdcStockID1.setFNumber("MF");
        fdcStockID1.setFName("");
        page2.setFDCStockID1(fdcStockID1);

        /*计划模式*/
        com.hanhai.material.device.model.miscellaneousdelivery.FPlanMode fPlanMode = new com.hanhai.material.device.model.miscellaneousdelivery.FPlanMode();
        fPlanMode.setFNumber("MTS");
        fPlanMode.setFName("");

        page2.setFPlanMode(fPlanMode);
        page2.setFnote(document.getNote());

        page2List.add(page2);

        data.setPage1(page1List);
        data.setPage2(page2List);
        miscellaneousDelivery.setData(data);
        miscellaneousDelivery.setFBillNo(document.getKingNo());
        return miscellaneousDelivery;
    }


    //    @Scheduled(initialDelay = 1, fixedRateString = "300000")
    public void getPDList() throws IOException {
        LocalDateTime localDateTime = LocalDateTime.now();
        LocalDate localDate = LocalDate.now();
        LocalDateTime targetTime1 = localDate.atTime(7, 45, 0);
        LocalDateTime targetTime2 = localDate.atTime(8, 15, 0);
        LocalDateTime targetTime3 = localDate.atTime(19, 45, 0);
        LocalDateTime targetTime4 = localDate.atTime(20, 15, 0);
        int hour = localDateTime.getHour();
        int minutes = localDateTime.getMinute();
        if ((localDateTime.isBefore(targetTime1) || localDateTime.isAfter(targetTime2)) && (localDateTime.isBefore(targetTime3) || localDateTime.isAfter(targetTime4))) {
            String token = this.createToken();
            String url = baseUrl + "/PD/GetList?token=" + token;
            RestTemplate restTemplate = new RestTemplate();
            HttpHeaders headers = new HttpHeaders();
            MediaType type = MediaType.parseMediaType("application/json;charset=UTF-8");
            headers.setContentType(type);
            Map<Object, Object> map = MapBuilder.create().put("Data",
                    MapBuilder.create()
                            .put("Top", "500")
                            .put("PageSize", "500")
                            .put("PageIndex", "1")
//                        .put("Filter","[FStatus] =1")
                            .put("OrderBy", "[FBillNo] DESC")
                            .put("SelectPage", "1").build()).build();
            HttpEntity<Map<Object, Object>> httpEntity = new HttpEntity<>(map, headers);
            ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, httpEntity, String.class);
            JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(responseEntity));
            log.error("Json:" + jsonObject.getJSONObject("body"));
            JSONObject body = jsonObject.getJSONObject("body");
            log.error("Json:" + body);
            JSONObject Data = body.getJSONObject("Data");
            log.error("Data:" + Data);
            JSONArray jsonArray = Data.getJSONArray("DATA");
            log.error("JSONArray:" + jsonArray);
            for (Object object : jsonArray) {
                String billNo = JSONObject.parseObject(JSONObject.toJSONString(object)).getString("FBillNo");
                log.error("BillNo:" + billNo);
                getPDDetail(billNo);
            }
            getPPBOMList();
        }
    }

    @Autowired
    SysWorkPlanService sysWorkPlanService;

    @Autowired
    SysProductRecordService sysProductRecordService;
    @Autowired
    SysProductRecordShiftService sysProductRecordShiftService;

    public void getPDDetail(String billNo) throws IOException {
        String token = this.createToken();

        String url = baseUrl + "/PD/GetDetail?token=" + token;
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json;charset=UTF-8");
        headers.setContentType(type);
        Map<Object, Object> map = MapBuilder.create().put("Data",
                MapBuilder.create().put("FBillNo", billNo).build()).build();
        HttpEntity<Map<Object, Object>> httpEntity = new HttpEntity<>(map, headers);
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, httpEntity, String.class);
        JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(responseEntity));
        JSONObject body = jsonObject.getJSONObject("body");
        log.error("Json:" + body);
        com.hanhai.material.device.model.workplan.Data data = body.getObject("Data", com.hanhai.material.device.model.workplan.Data.class);
        com.hanhai.material.device.model.workplan.Page1 page = data.getPage1().get(0);
        SysWorkPlan sysWorkPlan = new SysWorkPlan();
        sysWorkPlan.setId(page.getFBillNo());
        sysWorkPlan.setWorkPlanId(page.getFBillNo());
        sysWorkPlan.setProductName(page.getFItemName());
        sysWorkPlan.setPlanStartTime(page.getFPlanCommitDate());
        sysWorkPlan.setPlanEndTime(page.getFPlanFinishDate());
        sysWorkPlan.setProductNum(page.getFauxqty());
        sysWorkPlan.setMachineName(page.getFHeadSelfJ01100().getFName());
        sysWorkPlan.setActualStartTime(page.getFStartDate());
        sysWorkPlan.setWorkShop(page.getFWorkShop().getFName());
        sysWorkPlan.setMaterialId(page.getFHeadSelfJ01101());
        sysWorkPlan.setMaterialName(page.getFHeadSelfJ01106());
        sysWorkPlan.setGenerateDateTime(page.getFCheckDate());
        sysWorkPlan.setCloseDateTime(page.getFCloseDate());
        sysWorkPlan.setWorkPlanType(page.getFWorktypeID().getFName());
        sysWorkPlan.setMaterialNum(page.getFHeadSelfJ01102());
        sysWorkPlan.setProductId(page.getFItemID().getFNumber());
        sysWorkPlan.setDistributeManagerId(fManagerId);
        sysWorkPlan.setReceiveManagerId(sManagerId);
        sysWorkPlan.setWorkShopId(page.getFWorkShop().getFNumber());
        sysWorkPlan.setUnitId(page.getFUnitID().getFNumber());
        sysWorkPlan.setUnitName(page.getFUnitID().getFName());
        sysWorkPlan.setInterId(page.getFInterID());
        sysWorkPlan.setSourceEntryId(page.getFSourceEntryID());
        sysWorkPlan.setTranTypeId(page.getFTranType());
        sysWorkPlan.setProductStatus(page.getFstatus());
        sysWorkPlan.setShortName(page.getFHeadSelfJ01112());
        sysWorkPlan.setMoldNo(page.getFHeadSelfJ01107().getFNumber());

        if (page.getFHeadSelfJ01117() > 0) {
            sysWorkPlan.setQuantity((int) (1 / page.getFHeadSelfJ01117()));

        } else {
            sysWorkPlan.setQuantity(1);
        }
        try {
            sysWorkPlan.setMoldNumber(Double.parseDouble(page.getFHeadSelfJ01113()));
        } catch (Exception e) {
            sysWorkPlan.setMoldNumber(1);
        }

        if (page.getFHeadSelfJ01116() == null) {
            sysWorkPlan.setMoldSame(false);
        } else if ("共用".equals(page.getFHeadSelfJ01116())) {
            sysWorkPlan.setMoldSame(true);
        }
        sysWorkPlan.setPaperBoxNumber(page.getFHeadSelfJ01114());
        if ("数量切换".equals(page.getFHeadSelfJ01115().getFName())) {
            sysWorkPlan.setExchangeType("数量切换");
        } else if ("小工单切换".equals(page.getFHeadSelfJ01115().getFName())) {
            sysWorkPlan.setExchangeType("小工单切换");
        } else {
            sysWorkPlan.setExchangeType("自动切换");
        }
        QueryWrapper queryWrapper = QueryWrapper.create();
        queryWrapper.where(SYS_PRODUCT_RECORD.WORK_PLAN_ID.eq(sysWorkPlan.getWorkPlanId()));
        List<SysProductRecord> sysProductRecordList = this.sysProductRecordService.list(queryWrapper);
        if (sysProductRecordList.size() > 0) {
            for (SysProductRecord sysProductRecord : sysProductRecordList) {
                sysProductRecord.setExchangeType(sysWorkPlan.getExchangeType());
                sysProductRecord.setQuantity(sysWorkPlan.getQuantity());
            }
            this.sysProductRecordService.updateBatch(sysProductRecordList);
            queryWrapper = QueryWrapper.create();
            queryWrapper.where(SYS_PRODUCT_RECORD_SHIFT.WORK_PLAN_ID.eq(sysWorkPlan.getWorkPlanId()));
            List<SysProductRecordShift> sysProductRecordShiftList = this.sysProductRecordShiftService.list(queryWrapper);
            for (SysProductRecordShift sysProductRecordShift : sysProductRecordShiftList) {
                sysProductRecordShift.setExchangeType(sysWorkPlan.getExchangeType());
                sysProductRecordShift.setQuantity(sysWorkPlan.getQuantity());
            }
            this.sysProductRecordShiftService.updateBatch(sysProductRecordShiftList);
        }
        sysWorkPlan.setPaperBoxNumber(page.getFHeadSelfJ01114());
        SysWorkPlan sysWorkPlan1 = this.sysWorkPlanService.getById(sysWorkPlan.getWorkPlanId());
        if (sysWorkPlan1 == null) {
            sysWorkPlan.setEnd(false);
            this.sysWorkPlanService.save(sysWorkPlan);
        } else {
            this.sysWorkPlanService.updateById(sysWorkPlan);
        }
    }


    public void getPPBOMList() throws IOException {
        String token = null;
        if (this.redisUtil.get("token-king") == null) {
            token = this.createToken();
        } else {
            token = this.redisUtil.get("token-king").toString();
        }
        String url = baseUrl + "/PPBOM/GetList?token=" + token;
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json;charset=UTF-8");
        headers.setContentType(type);
        Map<Object, Object> map = MapBuilder.create().put("Data",
                MapBuilder.create()
                        .put("Top", "200")
                        .put("PageSize", "200")
                        .put("PageIndex", "1")
                        .put("OrderBy", "[FBillNo] DESC")
                        .put("SelectPage", "1").build()).build();
        HttpEntity<Map<Object, Object>> httpEntity = new HttpEntity<>(map, headers);
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, httpEntity, String.class);
        JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(responseEntity));
        log.error("Json:" + jsonObject.getJSONObject("body"));
        JSONObject body = jsonObject.getJSONObject("body");
        log.error("Json:" + body);
        JSONObject Data = body.getJSONObject("Data");
        log.error("Data:" + Data);
        JSONArray jsonArray = Data.getJSONArray("DATA");
        log.error("JSONArray:" + jsonArray);
        for (Object object : jsonArray) {
            log.error("OBject:{}", JSONObject.toJSONString(object));
            String billNo = JSONObject.parseObject(JSONObject.toJSONString(object)).getString("FBillNo");
            log.error("BillNo:" + billNo);
            getPPBOMDetail1(billNo);
        }
    }

    @Autowired
    SysBomService sysBomService;
    @Autowired
    SysBomChildService sysBomChildService;

    public List<SysBomChild> getPPBOMDetail(String billNo) throws IOException {
        String token = this.createToken();

        String url = baseUrl + "/PPBOM/GetDetail?token=" + token;
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json;charset=UTF-8");
        headers.setContentType(type);
        Map<Object, Object> map = MapBuilder.create().put("Data",
                MapBuilder.create().put("FBillNo", billNo).build()).build();
        HttpEntity<Map<Object, Object>> httpEntity = new HttpEntity<>(map, headers);
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, httpEntity, String.class);
        JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(responseEntity));
        JSONObject body = jsonObject.getJSONObject("body");
        List<SysBomChild> bomChildList = new ArrayList<>();

        if (body.getInteger("StatusCode") == 200) {
            log.error("Json:" + body);
            Bom bom = body.getObject("Data", Bom.class);
            com.hanhai.material.model.bom.Page1 page1 = bom.getPage1().get(0);
            SysBom sysBom = new SysBom();
            sysBom.setId(page1.getFBillNo());
            sysBom.setProductId(page1.getFItemID().getFNumber());
            sysBom.setProductName(page1.getFItemName());
            sysBom.setProductDate(page1.getFDate());
            sysBom.setProductIcmoId(page1.getFICMOInterID());
            sysBom.setProductWorkShopId(page1.getFWorkShop().getFNumber());
            sysBom.setProductWorkShopName(page1.getFWorkShop().getFName());
            sysBom.setClassTypeId(page1.getFClassTypeID());
            sysBom.setProductNum(BigDecimal.valueOf(page1.getFAuxQty()));
            sysBom.setMachineName(page1.getFHeadSelfY0229().getFName());
            QueryWrapper queryWrapper = QueryWrapper.create();
            queryWrapper.where(SYS_BOM.PRODUCT_ICMO_ID.eq(page1.getFICMOInterID()));
            queryWrapper.where(SYS_BOM.ID.eq(page1.getFBillNo()));
            queryWrapper.limit(1);
            SysBom oldBom = this.sysBomService.getOne(queryWrapper);
            if (oldBom != null) {
                queryWrapper = QueryWrapper.create();
                queryWrapper.where(SYS_BOM.ID.eq(page1.getFBillNo()));
               boolean result= this.sysBomService.remove(queryWrapper);
               if(result){
                   this.sysBomService.save(sysBom);

               }

            } else {
                this.sysBomService.save(sysBom);
            }
            List<com.hanhai.material.model.bom.Page2> page2List = bom.getPage2();
            List<SysBomChild> addBomChildList = new ArrayList<>();
            List<SysBomChild> updateBomChildList = new ArrayList<>();

            log.error("Page2Size:{}", page2List.size());

            for (com.hanhai.material.model.bom.Page2 page2 : page2List) {
                log.error("Page2:{}", page2.toString());
                SysBomChild sysBomChild = new SysBomChild();
                sysBomChild.setBomId(sysBom.getId());
                sysBomChild.setId(page2.getFBomDetailID1());
                sysBomChild.setAuxqtyPick(BigDecimal.valueOf(page2.getFAuxQtyPick1()));
                sysBomChild.setAuxStockQty(BigDecimal.valueOf(page2.getFAuxStockQty1()));
                sysBomChild.setStockId(page2.getFStockID1().getFNumber());
                sysBomChild.setStockName(page2.getFStockID1().getFName());
                sysBomChild.setStockPositionId(page2.getFPositionNo1());
                sysBomChild.setProductIcmoId(page2.getFICMOInterID1());
                sysBomChild.setUnitId(page2.getFUnitID1().getFNumber());
                sysBomChild.setUnitName(page2.getFUnitID1().getFName());
                sysBomChild.setMaterialId(page2.getFItemID1().getFNumber());
                sysBomChild.setMaterialName(page2.getFItemID1().getFName());
                sysBomChild.setEntryId(page2.getFEntryID1());
                sysBomChild.setUnitNum(BigDecimal.valueOf(page2.getFQtyScrap1()));
                sysBomChild.setStandardNum(BigDecimal.valueOf(page2.getFBOMInPutAuxQTY1()));
                sysBomChild.setInterId(page2.getFInterID1());
                sysBomChild.setHasGetNum(page2.getFEntrySelfY0277());
                SysBomChild oldSysBomChild = this.sysBomChildService.getById(sysBomChild.getId());

                bomChildList.add(sysBomChild);
                if (oldSysBomChild == null) {
                    addBomChildList.add(sysBomChild);
//                    this.sysBomChildService.save(sysBomChild);
                } else {
//                    this.sysBomChildService.updateById(sysBomChild);
                    updateBomChildList.add(sysBomChild);
                }
            }
            this.sysBomChildService.saveBatch(addBomChildList);
            this.sysBomChildService.updateBatch(updateBomChildList);

        }

        return bomChildList;
    }

    public SysBom getPPBOMDetail1(String billNo) throws IOException {
        String token = this.createToken();

        String url = baseUrl + "/PPBOM/GetDetail?token=" + token;
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json;charset=UTF-8");
        headers.setContentType(type);
        Map<Object, Object> map = MapBuilder.create().put("Data",
                MapBuilder.create().put("FBillNo", billNo).build()).build();
        HttpEntity<Map<Object, Object>> httpEntity = new HttpEntity<>(map, headers);
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, httpEntity, String.class);
        JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(responseEntity));
        JSONObject body = jsonObject.getJSONObject("body");
        List<SysBomChild> bomChildList = new ArrayList<>();

        if (body.getInteger("StatusCode") == 200) {
            log.error("Json:" + body);
            Bom bom = body.getObject("Data", Bom.class);
            com.hanhai.material.model.bom.Page1 page1 = bom.getPage1().get(0);
            SysBom sysBom = new SysBom();
            sysBom.setId(page1.getFBillNo());
            sysBom.setProductId(page1.getFItemID().getFNumber());
            sysBom.setProductName(page1.getFItemName());
            sysBom.setProductDate(page1.getFDate());
            sysBom.setProductIcmoId(page1.getFICMOInterID());
            sysBom.setProductWorkShopId(page1.getFWorkShop().getFNumber());
            sysBom.setProductWorkShopName(page1.getFWorkShop().getFName());
            sysBom.setClassTypeId(page1.getFClassTypeID());
            sysBom.setProductNum(BigDecimal.valueOf(page1.getFAuxQty()));
            sysBom.setMachineName(page1.getFHeadSelfY0229().getFName());
            return sysBom;
        } else {
            return null;
        }


    }

    public void getBomDetail() throws IOException {
        LocalDate localDate = LocalDate.now();
        YearMonth yearMonth = YearMonth.of(localDate.getYear(), localDate.getMonthValue());
        YearMonth yearMonth1 = YearMonth.of(localDate.getYear(), localDate.getMonthValue());
        List<LocalDate> localDateList = getDatesOfMonth(yearMonth);
        QueryWrapper queryWrapper = QueryWrapper.create();
        queryWrapper.where(SYS_BOM.PRODUCT_DATE.between(localDateList.get(0).minusDays(5), localDateList.get(localDateList.size() - 1)));
        List<SysBom> bomList = this.sysBomService.list(queryWrapper);
        log.error("BomList:{}", bomList.toString());
        for (SysBom bom : bomList) {
            this.getPPBOMDetail(bom.getId().trim());
        }

    }


    public JSONObject addProductReceipte(Object object) throws IOException {
        String token = null;
        if (this.redisUtil.get("token-king") == null) {
            token = this.createToken();
        } else {
            token = this.redisUtil.get("token-king").toString();
        }
        String url = baseUrl + "/ProductReceipt/Save?token=" + token;
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json;charset=UTF-8");
        headers.setContentType(type);
        HttpEntity<Object> httpEntity = new HttpEntity<>(object, headers);
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, httpEntity, String.class);
        JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(responseEntity));
        log.error("Json:" + jsonObject.getJSONObject("body"));
        return jsonObject.getJSONObject("body");
    }


    public PickData materialUntilGet(SysWorkPlan sysWorkPlan, SysBomChild sysBomChild, double fqty) {
        log.error("领料");
        log.error("SBom:{}", sysBomChild);
        PickData pickData = new PickData();
        com.hanhai.material.device.model.pick.Page1 page1 = new com.hanhai.material.device.model.pick.Page1();
        page1.setFROB(1);

        FSManagerID fsManagerID = new FSManagerID();
        if (sysBomChild.getMaterialId().startsWith("7.Y")) {
            fsManagerID.setFNumber("HJ02209");
        } else {
            fsManagerID.setFNumber("HJ00051");
        }

        fsManagerID.setFName("");
        page1.setFSManagerID(fsManagerID);

        FDeptID fDeptID = new FDeptID();
        fDeptID.setFNumber(sysWorkPlan.getWorkShopId());
        fDeptID.setFName("");
        page1.setFDeptID(fDeptID);

//        FPurposeID fPurposeID = new FPurposeID();
//        fPurposeID.setFNumber("YBLL");
//        fPurposeID.setFName("");
//        page1.setFPurposeID(fPurposeID);

        FFManagerID ffManagerID = new FFManagerID();
        ffManagerID.setFNumber("HJ01849");
        ffManagerID.setFName("");
        page1.setFFManagerID(ffManagerID);


        FSCStockID fscStockID = new FSCStockID();
        if (sysBomChild.getMaterialId().startsWith("7.Y")) {
            fscStockID.setFNumber("IN1.052");
        } else {
            fscStockID.setFNumber("IN1.053");
        }

        fscStockID.setFName("");
        page1.setFSCStockID(fscStockID);
        page1.setFSelTranType("生产任务单");
        page1.setFBackFlushed("0");


        page1.setFHeadSelfB0441("SYSTEM1");
        String shift = "";
        Date now = new Date();
        LocalDate localDate = LocalDate.now();
        int currentHour = now.getHours();
        page1.setFHeadSelfB0437(fromDateToString("yyyy-MM-dd HH:mm:ss", now));
        if (currentHour >= 8 && currentHour < 20) {
            shift = "白班";
        } else {
            shift = "夜班";
        }
        if (currentHour >= 0 && currentHour < 8) {
//            this.date = moment(this.date).add(-1)
            localDate = localDate.minusDays(1);
        }
        Date fdate = Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
        page1.setFHeadSelfB0442(shift);
        page1.setFdate(fromDateToString("yyyy-MM-dd 00:00:00", fdate));

        com.hanhai.material.device.model.pick.Data data = new com.hanhai.material.device.model.pick.Data();
        List<com.hanhai.material.device.model.pick.Page1> page1List = new ArrayList<>();
        page1List.add(page1);
        data.setPage1(page1List);

        com.hanhai.material.device.model.pick.Page2 page2 = new com.hanhai.material.device.model.pick.Page2();
        page2.setFQty(String.valueOf(fqty));

        FReProduceType fReProduceType = new FReProduceType();
        fReProduceType.setFName("否");
        fReProduceType.setFNumber("");
        page2.setFReProduceType(fReProduceType);

        FUnitID fUnitID = new FUnitID();
        fUnitID.setFNumber(sysBomChild.getUnitId());
        fUnitID.setFName("");
        page2.setFUnitID(fUnitID);

        FItemID fItemID = new FItemID();
        fItemID.setFNumber(sysBomChild.getMaterialId().trim());
        fItemID.setFName("");
        page2.setFItemID(fItemID);

        page2.setFICMOBillNo(sysWorkPlan.getWorkPlanId());
        page2.setFauxqty(String.valueOf(fqty));


        page2.setFICMOInterID(sysWorkPlan.getInterId().toString());

        FCostOBJID fCostOBJIDObj = new FCostOBJID();
        fCostOBJIDObj.setFNumber(sysWorkPlan.getProductId());
        fCostOBJIDObj.setFName("");
        page2.setFCostOBJID(fCostOBJIDObj);
        try {
            page2.setFPPBomEntryID(sysBomChild.getEntryId().toString());
            page2.setFEntryID2(sysBomChild.getEntryId().toString());
        } catch (Exception e) {
            page2.setFPPBomEntryID("");
            page2.setFEntryID2("");
        }

        page2.setFSourceEntryID(sysBomChild.getProductIcmoId().toString());
        page2.setFSourceInterId(sysWorkPlan.getInterId().toString());
        page2.setFSourceBillNo(sysWorkPlan.getWorkPlanId());

        page2.setFEntrySelfB0461(sysWorkPlan.getMachineName());
        FSCStockID1 fscStockID1 = new FSCStockID1();
        fscStockID1.setFNumber(fscStockID.getFNumber());
        fscStockID1.setFName("");

        page2.setFSCStockID1(fscStockID1);

        page2.setFAuxQtyMust(sysBomChild.getAuxStockQty().toString());

        page2.setFQty(String.valueOf(fqty));
        page2.setFSourceTranType("85");
        List<com.hanhai.material.device.model.pick.Page2> page2List = new ArrayList<>();
        page2List.add(page2);
        data.setPage2(page2List);
        pickData.setData(data);
        return pickData;
    }

    public PickData materialUntilBack(SysWorkPlan sysWorkPlan, SysBomChild sysBomChild, double fqty) {
        log.error("退料");
        log.error("SBom:{}", sysBomChild);
        PickData pickData = new PickData();
        com.hanhai.material.device.model.pick.Page1 page1 = new com.hanhai.material.device.model.pick.Page1();
        page1.setFROB(-1);

        FSManagerID fsManagerID = new FSManagerID();
        fsManagerID.setFNumber("HJ01849");

        fsManagerID.setFName("");
        page1.setFSManagerID(fsManagerID);

        FDeptID fDeptID = new FDeptID();
        fDeptID.setFNumber(sysWorkPlan.getWorkShopId());
        fDeptID.setFName("");
        page1.setFDeptID(fDeptID);

//        FPurposeID fPurposeID = new FPurposeID();
//        fPurposeID.setFNumber("YBLL");
//        fPurposeID.setFName("");
//        page1.setFPurposeID(fPurposeID);

        FFManagerID ffManagerID = new FFManagerID();
        if (sysBomChild.getMaterialId().startsWith("7.Y")) {
            ffManagerID.setFNumber("HJ02209");
        } else {
            ffManagerID.setFNumber("HJ00051");
        }
        ffManagerID.setFName("");
        page1.setFFManagerID(ffManagerID);


        FSCStockID fscStockID = new FSCStockID();
        if (sysBomChild.getMaterialId().startsWith("7.Y")) {
            fscStockID.setFNumber("IN1.056");
        } else {
            fscStockID.setFNumber("IN1.056");
        }

        fscStockID.setFName("");
        page1.setFSCStockID(fscStockID);
        page1.setFSelTranType("生产任务单");
        page1.setFBackFlushed("0");


        page1.setFHeadSelfB0441("SYSTEM1");
        String shift = "";
        Date now = new Date();
        LocalDate localDate = LocalDate.now();
        int currentHour = now.getHours();
        page1.setFHeadSelfB0437(fromDateToString("yyyy-MM-dd HH:mm:ss", now));
        if (currentHour >= 8 && currentHour < 20) {
            shift = "白班";
        } else {
            shift = "夜班";
        }
        if (currentHour >= 0 && currentHour < 8) {
//            this.date = moment(this.date).add(-1)
            localDate = localDate.minusDays(1);
        }
        Date fdate = Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
        page1.setFHeadSelfB0442(shift);
        page1.setFdate(fromDateToString("yyyy-MM-dd 00:00:00", fdate));

        com.hanhai.material.device.model.pick.Data data = new com.hanhai.material.device.model.pick.Data();
        List<com.hanhai.material.device.model.pick.Page1> page1List = new ArrayList<>();
        page1List.add(page1);
        data.setPage1(page1List);

        com.hanhai.material.device.model.pick.Page2 page2 = new com.hanhai.material.device.model.pick.Page2();
        page2.setFQty(String.valueOf(-fqty));

        FReProduceType fReProduceType = new FReProduceType();
        fReProduceType.setFName("否");
        fReProduceType.setFNumber("");
        page2.setFReProduceType(fReProduceType);

        FUnitID fUnitID = new FUnitID();
        fUnitID.setFNumber(sysBomChild.getUnitId());
        fUnitID.setFName("");
        page2.setFUnitID(fUnitID);

        FItemID fItemID = new FItemID();
        fItemID.setFNumber(sysBomChild.getMaterialId().trim());
        fItemID.setFName("");
        page2.setFItemID(fItemID);

        page2.setFICMOBillNo(sysWorkPlan.getWorkPlanId());
        page2.setFauxqty(String.valueOf(-fqty));


        page2.setFICMOInterID(sysWorkPlan.getInterId().toString());

        page2.setFEntrySelfB0461(sysWorkPlan.getMachineName());

        FCostOBJID fCostOBJIDObj = new FCostOBJID();
        fCostOBJIDObj.setFNumber(sysWorkPlan.getProductId());
        fCostOBJIDObj.setFName("");
        page2.setFCostOBJID(fCostOBJIDObj);
        try {
            page2.setFPPBomEntryID(sysBomChild.getEntryId().toString());
            page2.setFEntryID2(sysBomChild.getEntryId().toString());
        } catch (Exception e) {
            page2.setFPPBomEntryID("");
            page2.setFEntryID2("");
        }

        page2.setFSourceEntryID(sysBomChild.getProductIcmoId().toString());
        page2.setFSourceInterId(sysWorkPlan.getInterId().toString());
        page2.setFSourceBillNo(sysWorkPlan.getWorkPlanId());
        FSCStockID1 fscStockID1 = new FSCStockID1();
        fscStockID1.setFNumber(fscStockID.getFNumber());
        fscStockID1.setFName("");
        page2.setFSCStockID1(fscStockID1);

        page2.setFAuxQtyMust(sysBomChild.getAuxStockQty().toString());

        page2.setFQty(String.valueOf(-fqty));
        page2.setFSourceTranType("85");
        List<com.hanhai.material.device.model.pick.Page2> page2List = new ArrayList<>();
        page2List.add(page2);
        data.setPage2(page2List);
        pickData.setData(data);
        return pickData;
    }

    public KingdeeResult addPick(PickData pickData1) throws IOException {
        String token = null;
//        if (this.redisUtil.get("token-king-device") == null) {
        token = this.createToken1();
//        } else {
//            token = this.redisUtil.get("token-king-device").toString();
//        }
        log.error("Token:{}", token);
        String url = baseUrl + "/PickList/Save?token=" + token;
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json;charset=UTF-8");
        headers.setContentType(type);
//        PickData pickData=materialUntil("-1","10","7.Y10A1A000025","WORK202312020022","24667","1.YD1PS9DBA001","5","100","02");
        PickData pickData = pickData1;
        Map<Object, Object> map = new HashMap<>();
//
        map.put("Data", MapBuilder.create().put("Page1", JSONObject.toJSONString(pickData.getData().getPage1())).put("Page2", JSONObject.toJSONString(pickData.getData().getPage2())).build());
//        map.put("Data","Data");
        HttpEntity<PickData> httpEntity = new HttpEntity<>(pickData, headers);

        log.error("Http:{}", JSONObject.toJSONString(httpEntity.getBody()));
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, httpEntity, String.class);
        Object object = JSONObject.parseObject(responseEntity.getBody());
        log.error("Result:{}", object);
        return JSONObject.parseObject(JSONObject.toJSONString(object), KingdeeResult.class);
    }

    public KingdeeResult addPick1(JSONObject jsonObject) throws IOException {
        String token = null;
//        if (this.redisUtil.get("token-king-device") == null) {
        token = this.createToken1();
//        } else {
//            token = this.redisUtil.get("token-king-device").toString();
//        }
        log.error("Token:{}", token);
        String url = baseUrl + "/PickList/Save?token=" + token;
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json;charset=UTF-8");
        headers.setContentType(type);
//        PickData pickData=materialUntil("-1","10","7.Y10A1A000025","WORK202312020022","24667","1.YD1PS9DBA001","5","100","02");

        HttpEntity<JSONObject> httpEntity = new HttpEntity<>(jsonObject, headers);

        log.error("Http:{}", JSONObject.toJSONString(httpEntity.getBody()));
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, httpEntity, String.class);
        Object object = JSONObject.parseObject(responseEntity.getBody());
        log.error("Result:{}", object);
        return JSONObject.parseObject(JSONObject.toJSONString(object), KingdeeResult.class);
    }
    public KingdeeResult addPick2(JSONObject jsonObject) throws IOException {
        String token = null;
//        if (this.redisUtil.get("token-king-device") == null) {
        token = this.createToken1();
//        } else {
//            token = this.redisUtil.get("token-king-device").toString();
//        }
        log.error("Token:{}", token);
        String url = baseUrl + "/Transfer/Save?token=" + token;
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json;charset=UTF-8");
        headers.setContentType(type);
//        PickData pickData=materialUntil("-1","10","7.Y10A1A000025","WORK202312020022","24667","1.YD1PS9DBA001","5","100","02");

        HttpEntity<JSONObject> httpEntity = new HttpEntity<>(jsonObject, headers);

        log.error("Http:{}", JSONObject.toJSONString(httpEntity.getBody()));
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, httpEntity, String.class);
        Object object = JSONObject.parseObject(responseEntity.getBody());
        log.error("Result:{}", object);
        return JSONObject.parseObject(JSONObject.toJSONString(object), KingdeeResult.class);
    }

    public JSONObject getMaterialDetail(String materialId) throws IOException {
        String token = null;
        if (this.redisUtil.get("material-token-king") == null) {
            token = this.createToken();
        } else {
            token = this.redisUtil.get("material-token-king").toString();
        }
        String url = baseUrl + "/Material/GetDetail?token=" + token;
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json;charset=UTF-8");
        headers.setContentType(type);
        Map<Object, Object> map = MapBuilder.create().put("Data",
                MapBuilder.create().put("FNumber", materialId).build()).build();
        HttpEntity<Map<Object, Object>> httpEntity = new HttpEntity<>(map, headers);
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, httpEntity, String.class);
        JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(responseEntity));
        return jsonObject.getJSONObject("body");
    }
}
